<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\matchingRule\logic;

use plugin\saiadmin\basic\BaseLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Helper;
use app\matchingRule\model\MatchingRule;

/**
 * 匹配规则逻辑层
 */
class MatchingRuleLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new MatchingRule();
    }

    /**
     * 数据修改
     */
    public function update($data, $where)
    {
        if (!isset($data['parent_id'])) {
            $data['parent_id'] = 0;
        }
        if ($data['parent_id'] == $where['rule_id']) {
            throw new ApiException('不能设置父级为自身');
        }
        return $this->model->update($data, $where);
    }

    /**
     * 数据删除
     */
    public function destroy($ids, $force = false)
    {
        $num = $this->model->where('parent_id', 'in', $ids)->count();
        if ($num > 0) {
            throw new ApiException('该分类下存在子分类，请先删除子分类');
        } else {
            return $this->model->destroy($ids, $force);
        }
    }

    /**
     * 树形数据
     */
    public function tree($where)
    {
    $query = $this->search($where);
    if (request()->input('tree', 'false') === 'true') {
    $query->field('rule_id as id, rule_id as value, rule_name_zh as label, parent_id,is_required')->order('rule_sort desc,create_time desc');
    }else{
        $query->field('rule_id as id, rule_id as value,rule_id, rule_name_zh as label, parent_id,
        rule_name_zh,rule_name_en,rule_name_ja,rule_name_ko,
        rule_level,rule_type,rule_sort,is_required,create_time,is_required')->order('rule_sort desc,create_time desc');    
    }
    
     
    $data = $this->getAll($query);
    return Helper::makeTree($data);
    }
     public function buildTree(array $data, $parentId = 0) {
        $tree = [];
        foreach ($data as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->buildTree($data, $item['rule_id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    

}
